package com.yuyou.fn.tms.service.impl;

import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.educational.entity.BaseGrade;
import com.yuyou.fn.educational.entity.Student;
import com.yuyou.fn.educational.service.IBaseGradeService;
import com.yuyou.fn.educational.service.IStudentService;
import com.yuyou.fn.educational.vo.StudentSaveOrUpdateVo;
import com.yuyou.fn.tms.service.IStudentQueryService;
import com.yuyou.fn.tms.vo.FindOrSaveStudentParam;
import com.yuyou.fn.tms.vo.TmsStudent;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class StudentQueryServiceImpl implements IStudentQueryService {

    @Resource
    private IStudentService studentService ;

    @Resource
    private IBaseGradeService baseGradeService;

    @Override
    public TmsStudent query(FindOrSaveStudentParam findOrSaveStudentParam) {

        Student student = studentService.findByCID(findOrSaveStudentParam.getCID());

        if(student != null ){
            return new TmsStudent(student,null,null);
        }

        BaseGrade baseGrade = baseGradeService.findGradeByGradeName(findOrSaveStudentParam.getGraName());

        StudentSaveOrUpdateVo studentSaveOrUpdateVo = new StudentSaveOrUpdateVo();
        studentSaveOrUpdateVo.setName(findOrSaveStudentParam.getName());
        studentSaveOrUpdateVo.setPhoneNo(findOrSaveStudentParam.getPhone_no());
        studentSaveOrUpdateVo.setSex(findOrSaveStudentParam.getSex());
        studentSaveOrUpdateVo.setCid(findOrSaveStudentParam.getCID());
        studentSaveOrUpdateVo.setSchool(findOrSaveStudentParam.getSchool());
        studentSaveOrUpdateVo.setBirthday(findOrSaveStudentParam.getStuBirthDay());
        if(baseGrade != null ){
            studentSaveOrUpdateVo.setGradeId(baseGrade.getGradeId());
            studentSaveOrUpdateVo.setGradeName(baseGrade.getGradeName());
        }

        try{
            Long studentId = studentService.saveOrUpdateStudent(studentSaveOrUpdateVo);
            return new TmsStudent(studentService.findById(studentId) , null  , null ) ;
        }catch (BusException e){
            if(e.getMessage().contains("存在")){
                return new TmsStudent(studentService.findByNameAndPhone(findOrSaveStudentParam.getName(),findOrSaveStudentParam.getPhone_no()),null , null ) ;
            }else{
                throw  e ;
            }
        }
    }
}
